<template>
  <el-dialog :visible.sync="dialogFormVisible" :show-close="false" append-to-body :fullscreen="true" :before-close="stop">
    <div class="qrcode">
      <div id="reader" />
    </div>
    <div slot="title" class="dialog-footer">
      <el-button @click="stop">取 消</el-button>
      <el-button type="primary" @click="stop">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { Html5Qrcode } from 'html5-qrcode'
export default {
  name: 'BarScanIndex',
  data() {
    return {
      dialogFormVisible: false
    }
  },

  methods: {
    getCameras() {
      this.dialogFormVisible = true
      Html5Qrcode.getCameras()
        .then((devices) => {
          if (devices && devices.length) {
            this.html5QrCode = new Html5Qrcode('reader')
            this.start()
          }
        })
        .catch(() => {
          // handle err
          this.html5QrCode = new Html5Qrcode('reader')
          this.error = 'ERROR: 您需要授予相机访问权限'
          this.$emit('err', this.error)
        })
    },
    start() {
      // environment后置 user前置
      this.html5QrCode
        .start(
          { facingMode: 'environment' },
          {
            fps: 2,
            qrbox: { width: 250, height: 250 }
          },
          (decodedText, decodedResult) => {
            this.$emit('ok', decodedText)
          }
        )
        .catch((err) => {
          this.$emit('err', err)
        })
    },
    stop() {
      this.dialogFormVisible = false
      this.html5QrCode.stop().then((ignore) => {
        // QR Code scanning is stopped.
        console.log('QR Code scanning stopped.')
      })
        .catch(() => {
          // Stop failed, handle it.
          console.log('Unable to stop scanning.')
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.qrcode {
  width: 100%;
  height: 100%;
}
</style>
